package com.yimi.yinhepda.db.dao;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.pda.ym.db.dao.IDeptTableDao;
import com.pda.ym.utils.Constants;
import com.yimi.yinhepda.base.BaseApplication;
import com.yimi.yinhepda.db.helper.DbHelper;
import com.yimi.yinhepda.db.table.DepartmentTable;
import com.pda.uce.commom.util.LogUtil;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 000432
 * @date 2017/4/14
 * 网点部门表操作
 */
@Route(path = Constants.YM_IDEPTDAO_IMPL)
public class DepartmentTableDao extends BaseDao<DepartmentTable, Long> implements IDeptTableDao {
    private static final String TAG = SortScanTableDao.class.getSimpleName();

    public DepartmentTableDao() {
        super(DbHelper.getInstance(BaseApplication.getContext()), DepartmentTable.class);
    }

    public void createOrUpdate(List<DepartmentTable> list) {
        SQLiteDatabase database = getDbHelper().getWritableDatabase();
        String tableName = dao.getTableName();
        StringBuffer sql = new StringBuffer("replace into ");
        sql.append(tableName);
        sql.append("(deptBaseInfoId,");
        sql.append("column26,");
        sql.append("belongForward,");
        sql.append("deptCode,");
        sql.append("deptName,");
        sql.append("deptPinyin,");
        sql.append("enableTime,");
        sql.append("deptType,");
        sql.append("outDeptName,");
        sql.append("belongComp,");
        sql.append("districtCode,");
        sql.append("status,");
        sql.append("parentGroupCode,");
        sql.append("belongCompAccount,");
        sql.append("isResidentDept,");
        sql.append("isCrossProvince,");
        sql.append("creater,");
        sql.append("createrTime,");
        sql.append("modifier,");
        sql.append("modifierTime,");
        sql.append("isDelete,");
        sql.append("latestTime,");
        sql.append("recordVersion,");
        sql.append("theProvinceCode,");
        sql.append("theProvinceName,");
        sql.append("theCityCode,");
        sql.append("theCityName,");
        sql.append("theCountyCode,");
        sql.append("theCountyName,");
        sql.append("compCode,");
        sql.append("isOmg)");
        //28
        sql.append("values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
        LogUtil.e("sql=" + sql.toString());

        database.beginTransaction();
        for (DepartmentTable item : list) {
            if(!item.getDeptName().contains("禁用")){
                Object[] values = new Object[]{
                        item.getDeptBaseInfoId(), item.getColumn26(), item.getBelongForward(), item.getDeptCode(), item.getDeptName(), item.getDeptPinyin(), item.getEnableTime(), item.getDeptType(),
                        item.getOutDeptName(), item.getBelongComp(), item.getDistrictCode(), item.getStatus(), item.getParentGroupCode(),
                        item.getBelongCompAccount(), item.getIsResidentDept(), item.getIsCrossProvince(), item.getCreater(), item.getCreaterTime(),
                        item.getModifier(), item.getModifierTime(), item.getIsDelete(), item.getLatestTime(), item.getRecordVersion(), item.getTheProvinceCode(),
                        item.getTheProvinceName(), item.getTheCityCode(), item.getTheCityName(), item.getTheCountyCode(), item.getTheCountyName(),
                        item.getCompCode(), item.getIsOmg()
                };
                database.execSQL(sql.toString(), values);
            }
        }
        database.setTransactionSuccessful();
        database.endTransaction();
    }

    /**
     * 根据网点编号查询
     */
    public List<DepartmentTable> queryDataByDeptCode(String str) {

        try {
            QueryBuilder<DepartmentTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.eq("deptCode", str);
            //.or().like("deptName", str + "%");
            where.and().ne("deptType", 0);
            where.and().ne("deptType", 1);
            where.and().ne("isDelete", 1);
            List<DepartmentTable> departmentTableList = queryBuilder.query();
            return departmentTableList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据网点编号查询网点
     */
    public DepartmentTable queryDeptByDeptCode(String str) {
        try {
            QueryBuilder<DepartmentTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.eq("deptCode", str);
            where.and().ne("deptType", 0);
            where.and().ne("deptType", 1);
            where.and().ne("isDelete", 1);
            DepartmentTable departmentTableList = queryBuilder.queryForFirst();
            return departmentTableList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<DepartmentTable> queryDataByBelongComp(String str) {
        try {
            QueryBuilder<DepartmentTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.like("belongComp", str + "%");
            where.and().ne("deptType", 0);
            where.and().ne("deptType", 1);
            where.and().ne("isDelete", 1);
            List<DepartmentTable> departmentTableList = queryBuilder.query();
            return departmentTableList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<DepartmentTable> findByDeptBaseInfoId(long deptBaseInfoId) {
        try {
            QueryBuilder<DepartmentTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.eq("deptBaseInfoId", deptBaseInfoId);

            List<DepartmentTable> listUnloadScanTable = queryBuilder.query();
            return listUnloadScanTable;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public String findOrderByLatestTime() {
        String lastTime = null;
        try {
            QueryBuilder<DepartmentTable, Long> queryBuilder = dao.queryBuilder().orderBy("latestTime", false).limit(1L);
            List<DepartmentTable> list = queryBuilder.query();
            if (list != null && list.size() > 0) {
                lastTime = list.get(0).getLatestTime();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return lastTime;
    }

    /**
     * 只查询latestTime字段的最新时间，可提高查询速度
     */
    @Override
    public String findOrderByLatestTime2() {
        String lastTime = null;
        try {
            QueryBuilder<DepartmentTable, Long> queryBuilder = dao.queryBuilder();
            queryBuilder.selectColumns("latestTime");
            queryBuilder.orderBy("latestTime", false).limit(1L);
            List<DepartmentTable> list = queryBuilder.query();
            if (list != null && list.size() > 0) {
                lastTime = list.get(0).getLatestTime();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return lastTime;
    }

    public List<DepartmentTable> queryDataByDeptCodes(List<String> deptCodes) {
        try {
            QueryBuilder<DepartmentTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.in("deptCode", deptCodes);
            List<DepartmentTable> departmentTableList = queryBuilder.query();
            return departmentTableList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<DepartmentTable> queryDataByDeptCodes(List<String> deptCodes, String deptNameCode) {
        try {
            QueryBuilder<DepartmentTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.in("deptCode", deptCodes);
            if (deptNameCode != null && !"".equals(deptNameCode)) {
                where.and().like("deptName", "%" + deptNameCode + "%");
                where.or().like("deptCode", "%" + deptNameCode + "%");
            }
            List<DepartmentTable> departmentTableList = queryBuilder.query();
            return departmentTableList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<DepartmentTable> queryDataNotDelete() {
        try {
            QueryBuilder<DepartmentTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.eq("isDelete", 0);
            where.and().ne("deptCode", "sxzhuohao");
            where.and().ne("deptType", 1);
            List<DepartmentTable> departmentTableList = queryBuilder.query();
            return departmentTableList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public List<DepartmentTable> queryDataForWithout() {
        try {
            QueryBuilder<DepartmentTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.eq("isDelete", 0);
            where.and().ne("deptCode", "sxzhuohao");
            where.and().in("deptType", 1, 2, 3, 4, 5, 6);
            List<DepartmentTable> departmentTableList = queryBuilder.query();
            return departmentTableList;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据sql语句查询
     *
     * @param sql sql语句
     * @return list
     */
    public List<DepartmentTable> queryDataBySql(String sql) {

        SQLiteDatabase database = getDbHelper().getWritableDatabase();
        List<DepartmentTable> list = new ArrayList<>();
        Cursor cursor = database.rawQuery(sql, null);
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                DepartmentTable table = new DepartmentTable();
//                table.setId(Long.parseLong(resultColumns[0]));
//                table.setDeptBaseInfoId(Long.parseLong(resultColumns[1]));
//                table.setDeptCode(resultColumns[2]);
//                table.setDeptName(resultColumns[3]);
//                table.setDeptPinyin(resultColumns[4]);
//                table.setEnableTime(resultColumns[5]);
//                table.setDeptType(Integer.parseInt(resultColumns[6]));
//                table.setOutDeptName(resultColumns[7]);
//                table.setBelongComp(resultColumns[8]);
//                table.setDistrictCode(resultColumns[9]);
//                table.setStatus(Integer.parseInt(resultColumns[10]));
//                table.setParentGroupCode(resultColumns[11]);
//                table.setBelongCompAccount(resultColumns[12]);
//                table.setIsResidentDept(Integer.parseInt(resultColumns[13]));
//                table.setIsCrossProvince(Integer.parseInt(resultColumns[14]));
//                table.setCreater(resultColumns[15]);
//                table.setCreaterTime(resultColumns[16]);
//                table.setModifier(resultColumns[17]);
//                table.setModifierTime(resultColumns[18]);
//                table.setIsDelete(Integer.parseInt(resultColumns[19]));
//                table.setLatestTime(resultColumns[20]);
//                table.setRecordVersion(Integer.parseInt(resultColumns[21]));
//                table.setTheProvinceCode(Integer.parseInt(resultColumns[22]));
//                table.setTheProvinceName(resultColumns[23]);
//                table.setTheCityCode(Integer.parseInt(resultColumns[24]));
//                table.setTheCityName(resultColumns[25]);
//                table.setTheCountyCode(Integer.parseInt(resultColumns[26]));
//                table.setTheCountyName(resultColumns[27]);
//                table.setCompCode(resultColumns[28]);
                list.add(table);
            }
            cursor.close();
        }
        return list;
    }

    /**
     * 查询网点类型，6-分拨自提，
     *
     * @param deptCode        当前登录部门
     * @param virtualDeptType 虚拟网点类型
     * @return list
     */
    public List<DepartmentTable> getZiTiDept(String deptCode, String virtualDeptType) {
        try {
            QueryBuilder<DepartmentTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.eq("belongForward", deptCode);
            where.and().eq("column26", virtualDeptType);
            return queryBuilder.query();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询虚拟网点：7-跨越虚拟网点
     *
     * @param deptCode        部门编码
     * @param virtualDeptType 虚拟网点类型
     * @return DepartmentTable
     */
    public DepartmentTable getDataByDeptType(String deptCode, String virtualDeptType) {
        try {
            QueryBuilder<DepartmentTable, Long> queryBuilder = dao.queryBuilder();
            Where where = queryBuilder.where();
            where.eq("deptCode", deptCode);
            where.and().eq("column26", virtualDeptType);
            where.and().eq("isDelete", 0);
            return queryBuilder.queryForFirst();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void init(Context context) {

    }
}
